import { defineStore } from 'pinia';
import { ref } from 'vue';
import api from '@/http/api';

export const useIconStore = defineStore('icon', () => {
  const iconList = ref([]);
  const loading = ref(false);

  const setIconList = (list) => {
    iconList.value = list;
  };

  const clearIconList = () => {
    iconList.value = [];
  };

  const getIconList = async() => {
    if (iconList.value && iconList.value.length > 0) {
      return iconList.value;
    }

    if (loading.value) {
      await sleep(100);
      return await getIconList();
    }

    loading.value = true;
    const res = await api.post('/icon/list').catch(() => {
      loading.value = false
    });
    if (res.code === '1') {
      loading.value = false;
      setIconList(res.data);
      return iconList.value;
    }
  };

  const sleep = async (d) => {
    return new Promise((resolve) => setTimeout(resolve, d))
  };

  return {
    getIconList,
    clearIconList
  };
});
